package com.hmall.order.task;

import com.hmall.common.client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/*
 *   Description MqTask
 *   @author zhangyan
 *   @time   2024/11/21
 */
@Slf4j
@Component // 将当前类标记为组件
public class MqListener {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailService orderDetailService;


    //监听死信队列消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.dead.queue"),
            exchange = @Exchange(name = "order.dead.exchange", type = ExchangeTypes.DIRECT),
            key = "order.dead.routing"
    ))
    public void handleOrder(String id) {
        //传入订单id
        log.info("死信队列的消息id:{}", id);
        Long lid = Long.valueOf(id);
        //根据订单id查询订单状态,如果还是1,表示订单已超时
        Order order = orderService.getById(lid);
        OrderDetail orderDetail = orderDetailService.findByOrderId(order.getId());
        if (order.getStatus() == 1) {
            //修改订单状态为5(已取消)
            orderService.updateStatusById(lid, 5);
            //调用用户服务更新库存
            itemClient.rebackStock(orderDetail.getItemId(), orderDetail.getNum());
        }

    }


    //方式二
    //延时队列
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.status.queue"),
            exchange = @Exchange(name = "order.status.exchange", type = ExchangeTypes.DIRECT,delayed = "true"),
            key = "order.status"
    ))
    public void handleOrderStatus(String id) {
        log.info("延时队列的消息id:{}", id);
    }
}
